<template>
  <div class="module-card">
    <div class="module-header">
      <h3>部门简介管理</h3>
      <button 
        @click="isEditing = true" 
        class="btn-primary" 
        v-if="!isEditing"
        :class="{ 'pulse-effect': hovered }"
        @mouseenter="hovered = true"
        @mouseleave="hovered = false"
      >
        编辑简介
      </button>
    </div>
    
    <!-- 显示模式 -->
    <div class="intro-content" v-if="!isEditing" :class="{ 'fade-in': !isEditing }">
      <div v-if="deptIntro.description" class="intro-display">
        <div v-html="deptIntro.description" class="rich-content"></div>
      </div>
      <div v-else class="no-data">
        <div class="empty-state">
          <i class="icon-file-text-o"></i>
          <p>暂无部门简介数据</p>
        </div>
      </div>
      
      <!-- 图片上传区域 -->
      <div class="image-upload-section" v-if="!isEditing">
        <h4>部门图片：</h4>
        <div class="image-container">
          <div class="image-preview" v-if="displayImageUrl()">
            <img 
              :src="displayImageUrl()" 
              alt="部门图片" 
              class="preview-img"
              @click="showImagePreview = true"
            />
            <button 
              @click.stop="removeImage" 
              class="remove-img-btn"
              :class="{ 'show': imgHovered && deptIntro.imageUrl }"
              @mouseenter="imgHovered = true"
              @mouseleave="imgHovered = false"
            >
              <i class="icon-trash-o"></i>
            </button>
          </div>
          
          <div class="upload-placeholder" v-else>
            <i class="icon-upload"></i>
            <p>点击上传部门图片</p>
            <p class="hint-text">支持JPG、PNG格式，建议尺寸1200×600</p>
          </div>
          
          <button 
            @click="triggerImageUpload" 
            class="btn-primary upload-btn"
          >
            <i class="icon-picture-o"></i> 上传图片
          </button>
          <input 
            ref="imageInput" 
            type="file" 
            accept="image/*" 
            @change="handleImageUpload" 
            class="image-input"
          />
        </div>
      </div>
    </div>
    
    <!-- 编辑模式 -->
    <div class="intro-editor" v-if="isEditing" :class="{ 'slide-in': isEditing }">
      <textarea 
        v-model="editContent" 
        rows="10" 
        placeholder="请输入部门简介内容..."
        class="content-editor"
      ></textarea>
      <div class="editor-actions">
        <button @click="cancelEdit" class="btn-secondary">取消</button>
        <button @click="saveIntro" class="btn-primary">
          <i class="icon-save"></i> 保存
        </button>
      </div>
    </div>
    
    <!-- 图片预览弹窗 -->
    <div 
      class="image-modal" 
      v-if="showImagePreview && displayImageUrl()"
      @click="showImagePreview = false"
    >
      <div class="modal-content" @click.stop>
        <img :src="displayImageUrl()" alt="部门图片预览" class="modal-img" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import defaultDeptImage from '@/assets/采播.jpg'

// 状态管理
const deptIntro = ref({ content: '', description: '', imageUrl: '' })
const editContent = ref('')
const isEditing = ref(false)
const imageInput = ref(null)
const hovered = ref(false)
const imgHovered = ref(false)
const showImagePreview = ref(false)
const hasFetchedData = ref(false)

// 计算属性：获取图片URL，如果没有则使用默认图片
const displayImageUrl = () => {
  return deptIntro.value.imageUrl || defaultDeptImage
}

// 获取部门简介
const fetchDeptIntro = async () => {
  try {
    const response = await fetch('http://localhost:8080/department/4')
    const result = await response.json()
    if (result.code === 200) {
      deptIntro.value = result.data
      editContent.value = result.data.description || ''
      hasFetchedData.value = true
    } else {
      console.error('获取部门简介失败:', result.message)
      // 显示本地存储的历史数据（如果有）
      loadLocalBackup()
    }
  } catch (error) {
    console.error('获取部门简介失败:', error)
    // API调用失败时，尝试加载本地存储的备份数据
    loadLocalBackup()
    // 显示错误提示
    showToast('无法连接到服务器，正在使用本地数据', 'warning')
  }
}

// 加载本地备份数据
const loadLocalBackup = () => {
  try {
    const backup = localStorage.getItem('deptIntroBackup')
    if (backup) {
      const data = JSON.parse(backup)
      deptIntro.value = data
      editContent.value = data.description || ''
    }
  } catch (error) {
    console.error('加载本地备份数据失败:', error)
  }
}

// 保存数据到本地备份
const saveToLocalBackup = () => {
  try {
    localStorage.setItem('deptIntroBackup', JSON.stringify(deptIntro.value))
  } catch (error) {
    console.error('保存到本地备份失败:', error)
  }
}

// 保存部门简介
const saveIntro = async () => {
  try {
    const response = await fetch('http://localhost:8080/department/update', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        departmentId: 4,
        description: editContent.value
      })
    })
    
    const result = await response.json()
    if (result.code === 200) {
      deptIntro.value.description = editContent.value
      saveToLocalBackup()
      isEditing.value = false
      showToast('保存成功', 'success')
    } else {
      // 即使API失败，也保存到本地
      deptIntro.value.description = editContent.value
      saveToLocalBackup()
      isEditing.value = false
      showToast('无法连接到服务器，但已保存本地数据', 'warning')
    }
  } catch (error) {
    console.error('保存部门简介失败:', error)
    // 保存到本地
    deptIntro.value.description = editContent.value
    saveToLocalBackup()
    isEditing.value = false
    showToast('无法连接到服务器，但已保存本地数据', 'warning')
  }
}

// 图片上传相关
const triggerImageUpload = () => {
  imageInput.value.click()
}

const handleImageUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型和大小
  const validTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!validTypes.includes(file.type)) {
    showToast('请上传JPG、PNG或GIF格式的图片', 'warning')
    return
  }
  
  if (file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过5MB', 'warning')
    return
  }

  // 本地预览功能 - 立即显示用户选择的图片
  const reader = new FileReader()
  reader.onload = (e) => {
    deptIntro.value.imageUrl = e.target.result
    saveToLocalBackup() // 保存到本地备份
  }
  reader.readAsDataURL(file)
  
  // 同时尝试上传到服务器
  const formData = new FormData()
  formData.append('image', file)
  formData.append('departmentId', 4)

  try {
    const response = await fetch('http://localhost:8080/department/uploadImage', {
      method: 'POST',
      body: formData
    })

    const result = await response.json()
    if (result.code === 200) {
      // 如果服务器返回了新的URL，使用服务器的URL
      deptIntro.value.imageUrl = result.data.imageUrl
      saveToLocalBackup()
      showToast('图片上传成功', 'success')
    } else {
      showToast(result.message || '图片上传失败，但已保存本地预览', 'warning')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    showToast('无法连接到服务器，但已保存本地预览', 'warning')
  }
  
  // 重置文件输入
  event.target.value = ''
}

// 移除图片
const removeImage = async () => {
  // 如果是默认图片，不执行删除操作
  if (!deptIntro.value.imageUrl) {
    showToast('默认图片无法删除', 'info')
    return
  }
  
  if (confirm('确定要删除这张图片吗？')) {
    try {
      const response = await fetch(`http://localhost:8080/department/removeImage?departmentId=4`, {
        method: 'DELETE'
      })
      
      const result = await response.json()
      if (result.code === 200 || !hasFetchedData.value) {
        // 如果是使用本地数据，也允许删除
        deptIntro.value.imageUrl = ''
        saveToLocalBackup()
        showToast('图片已删除', 'success')
      } else {
        showToast(result.message || '删除失败', 'error')
      }
    } catch (error) {
      console.error('删除图片失败:', error)
      // 即使API调用失败，如果是本地数据也允许删除
      if (!hasFetchedData.value) {
        deptIntro.value.imageUrl = ''
        saveToLocalBackup()
        showToast('已删除本地图片', 'success')
      } else {
        showToast('删除失败，请重试', 'error')
      }
    }
  }
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  editContent.value = deptIntro.value.description || ''
}

// 提示消息
const showToast = (message, type = 'info') => {
  // 创建toast元素
  const toast = document.createElement('div')
  toast.className = `toast ${type}`
  toast.textContent = message
  document.body.appendChild(toast)
  
  // 显示动画
  setTimeout(() => {
    toast.classList.add('show')
  }, 10)
  
  // 自动消失
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => {
      document.body.removeChild(toast)
    }, 300)
  }, 3000)
}

// 初始化
onMounted(() => {
  fetchDeptIntro()
})
</script>

<style scoped>
/* 基础样式 - 提升整体质感 */
.module-card {
  width: 100%;
  max-width: 1200px;
  margin: 24px auto;
  padding: 28px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  font-family: "Inter", system-ui, sans-serif;
}

.module-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

/* 头部样式 - 增强视觉层次 */
.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  margin-bottom: 24px;
  border-bottom: 1px solid #f5f5f5;
}

.module-header h3 {
  margin: 0;
  color: #1f2329;
  font-size: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.module-header h3::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 20px;
  background-color: #1890ff;
  border-radius: 2px;
  margin-right: 12px;
}

/* 按钮样式 - 优化交互反馈 */
.btn-primary, .btn-secondary {
  padding: 10px 20px;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  font-size: 15px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn-primary {
  background-color: #1890ff;
  color: #ffffff;
}

.btn-primary:hover {
  background-color: #40a9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.btn-primary:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
}

.btn-secondary {
  background-color: #f9fafb;
  color: #4b5563;
  border: 1px solid #f0f0f0;
}

.btn-secondary:hover {
  background-color: #f3f4f6;
  border-color: #e5e7eb;
}

/* 内容显示区域 - 优化阅读体验 */
.intro-content {
  transition: all 0.3s ease;
}

.intro-display {
  padding: 24px;
  border-radius: 10px;
  background-color: #fafafa;
  line-height: 1.8;
  color: #4b5563;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.rich-content {
  font-size: 16px;
}

.rich-content p {
  margin-bottom: 16px;
  text-align: justify;
}

.rich-content h4 {
  margin: 24px 0 12px;
  color: #1f2329;
  font-size: 18px;
  font-weight: 600;
}

.rich-content strong {
  color: #1f2329;
}

/* 无数据状态 - 提升视觉友好度 */
.no-data {
  padding: 60px 0;
}

.empty-state {
  text-align: center;
  color: #9ca3af;
  padding: 32px;
  background-color: #f9fafb;
  border-radius: 10px;
  border: 1px dashed #e5e7eb;
}

.empty-state .icon-file-text-o {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
  transition: all 0.3s ease;
}

.empty-state:hover .icon-file-text-o {
  opacity: 0.7;
  transform: scale(1.05);
}

.empty-state p {
  font-size: 16px;
  margin: 0;
  line-height: 1.5;
}

/* 图片上传区域 - 增强交互体验 */
.image-upload-section {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px dashed #e5e7eb;
}

.image-upload-section h4 {
  margin: 0 0 16px;
  color: #1f2329;
  font-size: 17px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.image-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 图片预览样式 */
.image-preview {
  position: relative;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #f9fafb;
}

.image-preview:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.preview-img {
  width: 100%;
  max-height: 450px;
  object-fit: contain;
  display: block;
  padding: 20px;
  transition: all 0.3s ease;
}

.image-preview:hover .preview-img {
  transform: scale(1.01);
}

/* 图片删除按钮 */
.remove-img-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  background-color: rgba(255, 77, 79, 0.9);
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  opacity: 0;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(255, 77, 79, 0.2);
}

.remove-img-btn.show {
  opacity: 1;
}

.remove-img-btn:hover {
  background-color: #ff4d4f;
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
}

/* 上传占位符 */
.upload-placeholder {
  border: 2px dashed #e5e7eb;
  border-radius: 10px;
  padding: 48px 24px;
  text-align: center;
  color: #9ca3af;
  transition: all 0.3s ease;
  background-color: #f9fafb;
}

.upload-placeholder:hover {
  border-color: #1890ff;
  background-color: #f0f7ff;
  color: #40a9ff;
}

.upload-placeholder .icon-upload {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
  transition: all 0.3s ease;
}

.upload-placeholder:hover .icon-upload {
  opacity: 0.8;
  transform: scale(1.05);
}

.upload-placeholder p {
  margin: 0 0 8px;
  font-size: 16px;
  line-height: 1.5;
}

.hint-text {
  font-size: 14px;
  color: #9ca3af;
  max-width: 500px;
  margin: 0 auto;
}

.upload-btn {
  align-self: flex-start;
  padding: 10px 20px;
}

.image-input {
  display: none;
}

/* 编辑模式 - 优化编辑器样式 */
.intro-editor {
  padding: 8px 0;
  animation: slideIn 0.3s ease;
}

.content-editor {
  width: 100%;
  padding: 16px;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  box-sizing: border-box;
  resize: vertical;
  font-family: inherit;
  font-size: 16px;
  line-height: 1.7;
  transition: all 0.3s ease;
  background-color: #f9fafb;
  color: #1f2329;
}

.content-editor:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.15);
  background-color: #ffffff;
}

.editor-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 图片预览弹窗 - 增强视觉层次 */
.image-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.85);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  opacity: 0;
  animation: fadeIn 0.3s ease forwards;
}

.modal-content {
  max-width: 90%;
  max-height: 90%;
  padding: 24px;
  position: relative;
  animation: zoomIn 0.3s ease;
}

.modal-img {
  max-width: 100%;
  max-height: 85vh;
  border-radius: 10px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
  object-fit: contain;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 20px;
}

/* 动画效果 - 优化过渡体验 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideIn {
  from { transform: translateY(12px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

@keyframes zoomIn {
  from { transform: scale(0.92); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

.pulse-effect {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(24, 144, 255, 0.4); }
  70% { box-shadow: 0 0 0 12px rgba(24, 144, 255, 0); }
  100% { box-shadow: 0 0 0 0 rgba(24, 144, 255, 0); }
}

/* 提示消息样式 - 提升视觉辨识度 */
.toast {
  position: fixed;
  top: 24px;
  right: 24px;
  padding: 14px 24px;
  border-radius: 8px;
  color: white;
  font-size: 15px;
  font-weight: 500;
  z-index: 1000;
  opacity: 0;
  transform: translateY(-20px);
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 8px;
}

.toast.show {
  opacity: 1;
  transform: translateY(0);
}

.toast.success {
  background-color: #52c41a;
}

.toast.error {
  background-color: #f5222d;
}

.toast.warning {
  background-color: #faad14;
}

.toast.info {
  background-color: #1890ff;
}

/* 响应式设计 - 适配不同屏幕 */
@media (max-width: 768px) {
  .module-card {
    margin: 16px;
    padding: 20px;
  }
  
  .module-header h3 {
    font-size: 18px;
  }
  
  .intro-display {
    padding: 16px;
  }
  
  .image-upload-section {
    margin-top: 24px;
    padding-top: 20px;
  }
  
  .upload-placeholder {
    padding: 32px 16px;
  }
  
  .btn-primary, .btn-secondary {
    padding: 9px 16px;
    font-size: 14px;
  }
  
  .modal-content {
    padding: 16px;
  }
  
  .modal-img {
    padding: 16px;
    max-height: 80vh;
  }
}

@media (max-width: 480px) {
  .module-card {
    margin: 8px;
    padding: 16px;
  }
  
  .module-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .editor-actions {
    flex-direction: column-reverse;
    gap: 8px;
  }
  
  .editor-actions button {
    width: 100%;
  }
  
  .modal-img {
    max-height: 75vh;
    padding: 12px;
  }
  
  .upload-placeholder .icon-upload {
    font-size: 36px;
  }
  
  .empty-state {
    padding: 24px 16px;
  }
  
  .empty-state .icon-file-text-o {
    font-size: 36px;
  }
}
</style>